<script lang="ts" setup>
import { ref, computed, onMounted, defineProps } from "vue";
import LzCommentAPI, { LzCommentPageQuery } from "@/api/content/lz-comment";
import { useUserStore } from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";

// 定义组件属性
const props = defineProps({
  articleId: {
    type: Number,
    required: true,
  },
});

// 定义评论类型接口
interface CommentItem {
  id: number;
  rootId: number;
  content: string;
  createBy?: number;
  createTime?: string;
  nickname?: string;
  avatar?: string;
  toCommentId?: number;
  toCommentUserId?: number;
  toCommentUserName?: string;
  replies?: CommentItem[];
}

const userStore = useUserStore();
const hasLogin = computed(() => userStore.userInfo?.username != undefined);
const userInfo = computed(() => userStore.userInfo);

// 评论分页请求参数
const pageRequest = ref<LzCommentPageQuery>({
  pageNum: 1,
  pageSize: 10,
  articleId: props.articleId, // 使用传入的文章ID
});

// 评论列表数据
const commentList = ref<any[]>([]); // 使用any类型避免类型不匹配问题
const loading = ref(false);
const total = ref(0);

// 新评论内容
const commentContent = ref("");
const replyContent = ref("");
const replyToComment = ref<CommentItem | null>(null);
const showReplyBox = ref(false);

// 初始化数据
onMounted(() => {
  initData();
});

// 获取评论列表
function initData() {
  loading.value = true;
  LzCommentAPI.getPage(pageRequest.value)
    .then((res) => {
      commentList.value = res.list || [];
      total.value = res.total || 0;
      loading.value = false;
    })
    .catch((error) => {
      console.error("获取评论列表失败:", error);
      loading.value = false;

      // 如果API调用失败，使用假数据进行测试
      useDummyData();
    });
}

// 使用假数据（仅用于开发测试）
function useDummyData() {
  const dummyComments: CommentItem[] = [
    {
      id: 1,
      rootId: -1,
      content: "这篇文章写得很好，内容很有深度！",
      nickname: "say.my.name",
      createTime: new Date(Date.now() - 40 * 60 * 1000).toISOString(),
      avatar: "https://via.placeholder.com/40/3498db/FFFFFF?text=S",
      createBy: 1,
    },
    {
      id: 2,
      rootId: 1,
      toCommentId: 1,
      toCommentUserId: 1,
      toCommentUserName: "say.my.name",
      content: "我也觉得，特别是第三部分的分析很到位",
      nickname: "狮山狂想曲",
      createTime: new Date(Date.now() - 31 * 60 * 1000).toISOString(),
      avatar: "https://via.placeholder.com/40/e74c3c/FFFFFF?text=狮",
      createBy: 2,
    },
    {
      id: 3,
      rootId: 1,
      toCommentId: 2,
      toCommentUserId: 2,
      toCommentUserName: "狮山狂想曲",
      content: "确实，我学到了很多新知识",
      nickname: "nstsd",
      createTime: new Date(Date.now() - 29 * 60 * 1000).toISOString(),
      avatar: "https://via.placeholder.com/40/2ecc71/FFFFFF?text=N",
      createBy: 3,
    },
    {
      id: 4,
      rootId: -1,
      content: "请问作者有没有相关的参考资料推荐？",
      nickname: "知识探索者",
      createTime: new Date(Date.now() - 24 * 60 * 1000).toISOString(),
      avatar: "https://via.placeholder.com/40/9b59b6/FFFFFF?text=知",
      createBy: 4,
    },
    {
      id: 5,
      rootId: 4,
      toCommentId: 4,
      toCommentUserId: 4,
      toCommentUserName: "知识探索者",
      content: "我在文章底部的参考文献列表里找到了一些相关资料，希望对你有帮助",
      nickname: "热心读者",
      createTime: new Date(Date.now() - 19 * 60 * 1000).toISOString(),
      avatar: "https://via.placeholder.com/40/f39c12/FFFFFF?text=热",
      createBy: 5,
    },
  ];

  commentList.value = dummyComments;
  total.value = dummyComments.length;
  loading.value = false;
}

// 处理分页变化
function handlePageChange(page: number) {
  pageRequest.value.pageNum = page;
  initData();
}

// 提交评论
function submitComment() {
  if (!hasLogin.value) {
    ElMessageBox.confirm("请先登录后再评论", "提示", {
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 跳转到登录页
        window.location.href = "/login";
      })
      .catch(() => {});
    return;
  }

  if (!commentContent.value.trim()) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  const params = {
    articleId: pageRequest.value.articleId,
    rootId: -1, // 顶级评论
    content: commentContent.value,
    toCommentUserId: -1, // 顶级评论没有回复目标
    toCommentId: -1, // 顶级评论没有回复目标
  };

  LzCommentAPI.add(params)
    .then(() => {
      ElMessage.success("评论成功");
      commentContent.value = ""; // 清空输入框
      initData(); // 重新加载评论列表
    })
    .catch((error) => {
      console.error("评论提交失败:", error);
      ElMessage.error("评论提交失败，请稍后重试");
    });
}

// 回复评论
function replyToUser(comment: CommentItem) {
  if (!hasLogin.value) {
    ElMessageBox.confirm("请先登录后再回复", "提示", {
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 跳转到登录页
        window.location.href = "/login";
      })
      .catch(() => {});
    return;
  }

  replyToComment.value = comment;
  showReplyBox.value = true;
  // 滚动到回复框
  setTimeout(() => {
    const replyBoxEl = document.getElementById(`reply-box-${comment.id}`);
    if (replyBoxEl) {
      replyBoxEl.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }, 100);
}

// 提交回复
function submitReply() {
  if (!replyContent.value.trim()) {
    ElMessage.warning("回复内容不能为空");
    return;
  }

  if (!replyToComment.value) {
    return;
  }

  const params = {
    articleId: pageRequest.value.articleId,
    rootId:
      +replyToComment.value.rootId === -1 ? replyToComment.value.id : replyToComment.value.rootId,
    content: replyContent.value,
    toCommentUserId: replyToComment.value.createBy,
    toCommentId: replyToComment.value.id,
  };

  LzCommentAPI.add(params)
    .then(() => {
      ElMessage.success("回复成功");
      replyContent.value = ""; // 清空输入框
      showReplyBox.value = false;
      replyToComment.value = null;
      initData(); // 重新加载评论列表
    })
    .catch((error) => {
      console.error("回复提交失败:", error);
      ElMessage.error("回复提交失败，请稍后重试");
    });
}

// 取消回复
function cancelReply() {
  showReplyBox.value = false;
  replyContent.value = "";
  replyToComment.value = null;
}

// 格式化时间
function formatTime(time: string | undefined): string {
  if (!time) return "";

  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1分钟
  if (diff < 60 * 1000) {
    return "刚刚";
  }

  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }

  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }

  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }

  // 大于30天，显示具体日期
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month < 10 ? "0" + month : month}-${day < 10 ? "0" + day : day}`;
}
</script>

<template>
  <div class="comment-section">
    <h3 class="comment-title">
      <i class="fa fa-comments me-2"></i>
      评论区
      <span class="comment-count">({{ total }})</span>
    </h3>

    <!-- 评论输入框 -->
    <div class="comment-form mb-4">
      <div class="d-flex align-items-start">
        <img
          v-if="hasLogin"
          :src="userInfo?.avatar"
          alt="User Avatar"
          class="comment-avatar me-3"
        />
        <img
          v-else
          src="@/assets/images/default.png"
          alt="User Avatar"
          class="comment-avatar me-3"
        />
        <div class="flex-grow-1">
          <div class="form-floating mb-3">
            <textarea
              id="commentTextarea"
              v-model="commentContent"
              class="form-control"
              placeholder="写下你的评论..."
              :disabled="!hasLogin"
              style="height: 100px"
            ></textarea>
            <label for="commentTextarea">写下你的评论...</label>
          </div>
          <div class="d-flex justify-content-between align-items-center">
            <small v-if="!hasLogin" class="text-muted">请先登录后再评论</small>
            <button
              class="btn btn-primary"
              :disabled="!hasLogin || !commentContent.trim()"
              @click="submitComment"
            >
              发表评论
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-if="loading" class="text-center py-4">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
    </div>

    <div v-else-if="commentList.length === 0" class="text-center py-4">
      <p class="text-muted">暂无评论，快来发表第一条评论吧！</p>
    </div>

    <div v-else class="comment-list">
      <!-- 顶级评论 -->
      <div v-for="comment in commentList" :key="comment.id" class="comment-item">
        <div class="d-flex">
          <img
            :src="comment.avatar || 'https://via.placeholder.com/40/95a5a6/FFFFFF?text=匿'"
            alt="User Avatar"
            class="comment-avatar me-3"
          />
          <div class="flex-grow-1">
            <div class="comment-header">
              <div>
                <span class="comment-author">{{ comment.nickName || "匿名用户" }}</span>
                <small class="text-muted ms-2">{{ formatTime(comment.createTime) }}</small>
              </div>
            </div>

            <div class="comment-content">
              <p>{{ comment.content }}</p>
            </div>

            <div class="comment-actions">
              <button
                class="btn btn-sm btn-link text-decoration-none"
                @click="replyToUser(comment)"
              >
                <i class="fa fa-reply me-1"></i>
                回复
              </button>
            </div>

            <!-- 回复框 -->
            <div
              v-if="showReplyBox && replyToComment && replyToComment.id === comment.id"
              :id="`reply-box-${comment.id}`"
              class="reply-form mt-3"
            >
              <div class="d-flex align-items-start">
                <img
                  :src="
                    hasLogin
                      ? userInfo?.avatar
                      : 'https://via.placeholder.com/30/95a5a6/FFFFFF?text=游'
                  "
                  alt="User Avatar"
                  class="reply-avatar me-2"
                />
                <div class="flex-grow-1">
                  <div class="form-floating mb-2">
                    <textarea
                      :id="`replyTextarea-${comment.id}`"
                      v-model="replyContent"
                      class="form-control"
                      :placeholder="`回复 ${comment.nickname || '用户'}...`"
                      style="height: 80px"
                    ></textarea>
                    <label :for="`replyTextarea-${comment.id}`">
                      回复 {{ comment.nickName || "用户" }}...
                    </label>
                  </div>
                  <div class="d-flex justify-content-end gap-2">
                    <button class="btn btn-sm btn-outline-secondary" @click="cancelReply">
                      取消
                    </button>
                    <button
                      class="btn btn-sm btn-primary"
                      :disabled="!replyContent.trim()"
                      @click="submitReply"
                    >
                      提交回复
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 回复列表 -->
            <div
              v-if="comment.children && comment.children.length > 0"
              class="replies-container mt-3"
            >
              <div v-for="reply in comment.children" :key="reply.id" class="reply-item">
                <div class="d-flex">
                  <img
                    :src="reply.avatar || 'https://via.placeholder.com/30/95a5a6/FFFFFF?text=匿'"
                    alt="User Avatar"
                    class="reply-avatar me-2"
                  />
                  <div class="flex-grow-1">
                    <div class="reply-header">
                      <div>
                        <span class="reply-author">{{ reply.nickName || "匿名用户" }}</span>
                        <small class="text-muted ms-2">{{ formatTime(reply.createTime) }}</small>
                      </div>
                    </div>

                    <div class="reply-content">
                      <span
                        v-if="reply.toCommentUserName && reply.toCommentId !== comment.id"
                        class="reply-to"
                      >
                        回复
                        <span class="reply-name">@{{ reply.toCommentUserName }}</span>
                        ：
                      </span>
                      <p>{{ reply.content }}</p>
                    </div>

                    <div class="reply-actions">
                      <button
                        class="btn btn-sm btn-link text-decoration-none"
                        @click="replyToUser(reply)"
                      >
                        <i class="fa fa-reply me-1"></i>
                        回复
                      </button>
                    </div>

                    <!-- 回复框 -->
                    <div
                      v-if="showReplyBox && replyToComment && replyToComment.id === reply.id"
                      :id="`reply-box-${reply.id}`"
                      class="reply-form mt-2"
                    >
                      <div class="d-flex align-items-start">
                        <img
                          :src="
                            hasLogin
                              ? userInfo?.avatar
                              : 'https://via.placeholder.com/30/95a5a6/FFFFFF?text=游'
                          "
                          alt="User Avatar"
                          class="reply-avatar me-2"
                        />
                        <div class="flex-grow-1">
                          <div class="form-floating mb-2">
                            <textarea
                              :id="`replyTextarea-${reply.id}`"
                              v-model="replyContent"
                              class="form-control"
                              :placeholder="`回复 ${reply.nickName || '用户'}...`"
                              style="height: 80px"
                            ></textarea>
                            <label :for="`replyTextarea-${reply.id}`">
                              回复 {{ reply.nickName || "用户" }}...
                            </label>
                          </div>
                          <div class="d-flex justify-content-end gap-2">
                            <button class="btn btn-sm btn-outline-secondary" @click="cancelReply">
                              取消
                            </button>
                            <button
                              class="btn btn-sm btn-primary"
                              :disabled="!replyContent.trim()"
                              @click="submitReply"
                            >
                              提交回复
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > pageRequest.pageSize" class="d-flex justify-content-center mt-4">
      <nav aria-label="Page navigation">
        <ul class="pagination">
          <li class="page-item" :class="{ disabled: pageRequest.pageNum === 1 }">
            <a
              class="page-link"
              href="#"
              @click.prevent="handlePageChange(pageRequest.pageNum - 1)"
            >
              <span aria-hidden="true">&laquo;</span>
            </a>
          </li>
          <li
            v-for="page in Math.ceil(total / pageRequest.pageSize)"
            :key="page"
            class="page-item"
            :class="{ active: page === pageRequest.pageNum }"
          >
            <a class="page-link" href="#" @click.prevent="handlePageChange(page)">{{ page }}</a>
          </li>
          <li
            class="page-item"
            :class="{ disabled: pageRequest.pageNum === Math.ceil(total / pageRequest.pageSize) }"
          >
            <a
              class="page-link"
              href="#"
              @click.prevent="handlePageChange(pageRequest.pageNum + 1)"
            >
              <span aria-hidden="true">&raquo;</span>
            </a>
          </li>
        </ul>
      </nav>
    </div>
  </div>
</template>

<style scoped lang="scss">
.comment-section {
  margin-top: 2rem;
  padding: 1.5rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.comment-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.75rem;

  .comment-count {
    font-size: 1rem;
    color: #6c757d;
    font-weight: normal;
  }
}

.comment-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.reply-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-item {
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
}

.comment-header {
  margin-bottom: 0.5rem;
  display: flex;
  justify-content: space-between;
}

.comment-author {
  font-weight: 600;
  color: #333;
}

.comment-content {
  margin-bottom: 0.5rem;

  p {
    margin-bottom: 0;
    word-break: break-word;
  }
}

.comment-actions {
  display: flex;
  gap: 1rem;
  margin-bottom: 0.5rem;

  .btn-link {
    color: #6c757d;
    padding: 0;

    &:hover {
      color: #0d6efd;
    }
  }
}

.replies-container {
  padding-left: 1.5rem;
  border-left: 2px solid #e9ecef;
}

.reply-item {
  padding: 0.75rem;
  margin-bottom: 0.75rem;
  background-color: #f8f9fa;
  border-radius: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.reply-header {
  margin-bottom: 0.25rem;
  display: flex;
  justify-content: space-between;
}

.reply-author {
  font-weight: 600;
  color: #333;
  font-size: 0.95rem;
}

.reply-content {
  margin-bottom: 0.25rem;

  p {
    margin-bottom: 0;
    word-break: break-word;
  }
}

.reply-to {
  color: #6c757d;
  font-size: 0.9rem;

  .reply-name {
    color: #0d6efd;
    font-weight: 500;
  }
}

.reply-actions {
  display: flex;
  gap: 0.5rem;

  .btn-link {
    color: #6c757d;
    padding: 0;
    font-size: 0.9rem;

    &:hover {
      color: #0d6efd;
    }
  }
}

.reply-form {
  background-color: #fff;
  padding: 0.75rem;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

// 响应式调整
@media (max-width: 768px) {
  .comment-section {
    padding: 1rem;
  }

  .comment-avatar {
    width: 40px;
    height: 40px;
  }

  .reply-avatar {
    width: 32px;
    height: 32px;
  }

  .replies-container {
    padding-left: 1rem;
  }
}

@media (max-width: 576px) {
  .comment-section {
    padding: 0.75rem;
  }

  .comment-title {
    font-size: 1.25rem;
  }

  .comment-avatar {
    width: 36px;
    height: 36px;
  }

  .reply-avatar {
    width: 28px;
    height: 28px;
  }

  .replies-container {
    padding-left: 0.5rem;
  }

  .reply-item {
    padding: 0.5rem;
  }

  .pagination {
    .page-link {
      padding: 0.25rem 0.5rem;
      font-size: 0.875rem;
    }
  }
}
</style>
